
var express = require('express');
var bodyParser = require('body-parser');
var cookieParser = require('cookie-parser');
var fs = require('fs');
var multer = require('multer')
var template = require('art-template');
var app = express();
app.engine('.html',template.__express);
app.set('view engine','html');
template.helper('ms',function(time){
    var time = new Date(time);
    return time.getTime();
})
template.helper('formatTime',function(time){
    var time = new Date(time);
    var year = time.getFullYear();
    var month = time.getMonth()+1;
    var day = time.getDate();
    month=month<10?'0'+month:month;
    day=day<10?'0'+day:day;
    return `${year}-${month}-${day}`;
})
var storage = multer.diskStorage({
    destination:'www/uploads',
    filename:function(req,file,callback){
        var petname = req.cookies.petname;
        callback(null,`${petname}.jpg`);
    }
})
var uploads=multer({storage});
app.use(bodyParser.urlencoded({extended:true}));
app.use(cookieParser());
app.use(express.static('www'));
app.post('/register',function(req,res){
    req.body.ip=req.ip;
    req.body.time=new  Date();
    function send(code,message){
        res.status(200).json({code,message});
    }
    function saveFile(){
        var filename=`users/${req.body.petname}.txt`;
        fs.exists(filename,function(exists){
            if(exists){
                send('error','用户名已经存在');
            }
            else{
                fs.appendFile(filename,JSON.stringify(req.body),function(err){
                    if (err){
                        send('error','系统错误');
                    }
                    else {
                        send('success','注册成功');
                    }
                })
            }
        })
    }
    fs.exists('users',function(exists){
        if(exists){
            saveFile();
        }
        else {
            fs.mkdir('users',function(err){
                if (err){
                    send('err','系统错误');
                }
                else {
                    saveFile();
                }
            })
        }
    })
})
app.post('/login',function(req,res){
    var filename=`users/${req.body.petname}.txt`;
    function send(code,message){
        res.status(200).json({code,message});
    }
    fs.exists(filename,function(exists){
       if(exists){
           fs.readFile(filename,function(err,data){
               if(err){
                   send('eror','系统错误')
               }
               else{
                   var user=JSON.parse(data);
                   if(user.password==req.body.password){
                       res.cookie('petname',req.body.petname);
                       send('success','登录成功');
                   }
                   else {
                       send('error','密码错误')
                   }
               }
           })
       }
        else {
           send('error','用户名不存在');
       }
    })
})
app.post('/ask',function(req,res){
    var petname=req.cookies.petname;
    req.body.ip=req.ip;
    var time =new Date();
    req.body.time=time;
    req.body.petname=petname;
    function send(code,message){
        res.status(200).json({code,message});
    }
    function saveFile(){
        var filename=`questions/${time.getTime()}.txt`;
        fs.exists(filename,function(exists){
            if(exists){
                send('error','系统错误');
            }else{
                fs.appendFile(filename,JSON.stringify(req.body),function(err){
                    if(err){
                        send('error','系统错误');
                    }else{
                        send('success','提问成功');
                    }
                })
            }
        })
    }
    fs.exists('questions',function(exists){
        if(exists){
            saveFile();
        }else{
            fs.mkdir('questions',function(err){
                if(err){
                    send('error','系统错误');
                }else{
                    saveFile();
                }
            })
        }
    })
})
app.get('/',function(req,res){
    function send(code,message,data){
        res.status(200).json({code,message,data});
    }
    function readFiles(i,files,questions,callback){
        if(i < files.length){
            fs.readFile(`questions/${files[i]}`,function(err,data){
                questions.push(JSON.parse(data));
                readFiles(++i,files,questions,callback);
            })
        }else{
            callback();
        }
    }
    fs.readdir('questions',function(err,file){
        if(err){
            send('error','文件读取失败');
        }else {
            file=file.reverse();
            var questions=[];
            readFiles(0,file,questions,function(){
                res.render('index',{
                    user:req.cookies.petname,
                    questions

                })
            })
        }
    })
})
app.post('/answer',function(req,res){
    function send(code,message){
        res.status(200).json({code,message});
    }
    var filename = `questions/${req.body.question}.txt`;
    var petname = req.cookies.petname;
    req.body.petname = petname;
    req.body.ip = req.ip;
    req.body.time = new Date();
    fs.readFile(filename,function(err,data){
        if(err){
            send('error','读取失败');
        }else{
            var question = JSON.parse(data);
            if(!question.answers) question.answers = [];
            question.answers.push(req.body);
            fs.writeFile(filename,JSON.stringify(question),function(err){
                if(err){
                    send('error','读取失败');
                }else{
                    send('success','读取成功');
                }
            })
        }
    })

})
function sign(req,res,next){
    if(req.cookies.petname){
        next();
    }else{
        res.redirect('/login');
    }
}
app.post('/user',uploads.single('photo'),function(req,res){
    res.status(200).json({code:'success',message:'发送成功'});
})
app.get('/login',function(req,res){
    res.render('login',{
        user:req.cookies.petname,
        title:'登录页面'
    })
})
app.get('/register',function(req,res){
    res.render('register',{
        user:req.cookies.petname,
        title:'注册页面'
    })
})
app.get('/ask',sign,function(req,res){
    res.render('ask',{
        user:req.cookies.petname,
        title:'提问页面'
    })
})
app.get('/answer/:question',sign,function(req,res){
    var question = req.params.question
    res.render('answer',{
        user:req.cookies.petname,
        question:question,
        title:'回答页面'
    })
})
app.get('/user',sign,function(req,res){
    res.render('user',{
        user:req.cookies.petname,
        title:'用户页面'
    })
})
app.get('/signout',function(req,res){
    res.clearCookie('petname');
    res.redirect('/');
})
app.listen(3000,function(){
    console.log('node is ok');
})